package cn.layfolk.seckill.web.controller;

import cn.layfolk.daimao.consts.ErrorCodeEnum;
import cn.layfolk.daimao.exception.MessageCenterException;
import cn.layfolk.daimao.vo.TUser;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import cn.layfolk.seckill.redis.SeckillRedisKey;
import cn.layfolk.seckill.service.TSeckillGoodsService;
import cn.layfolk.seckill.vo.SeckillGoodsVo;
import cn.layfolk.seckill.vo.reqvo.PathReqVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;



@RestController
public class PathController {

    @Autowired
    private TSeckillGoodsService seckillGoodsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/path")
    public ResponseVo<String> getPath(PathReqVo pathReqVo){

        //获取当前用户
        TUser user = null;
        if (user == null){
            throw new MessageCenterException(ErrorCodeEnum.USER_NOT_LOGIN);
        }

        // 校验验证码是否正确
        String ret  = stringRedisTemplate.opsForValue().get(SeckillRedisKey.SECKILL_VERIFY_CODE_RET.getRealKey(user.getId()+""));
        if (StringUtils.isEmpty(ret) || !pathReqVo.getVerifyCode().equals(ret)) {
            throw new MessageCenterException(ErrorCodeEnum.VERIFY_CODE_ERROR);

        }
        //1.先获取秒杀商品信息
        SeckillGoodsVo vo = seckillGoodsService.findByIdInCache(pathReqVo.getSeckillId());
        if (vo==null){
            throw new MessageCenterException(ErrorCodeEnum.OP_ERROR);
        }
        //2.判断当前时间是否在秒杀活动范围内
        Date now = new Date();
        //当前时间大于等于开始时间 and 小于等于结束时间
        if (now.compareTo(vo.getStartDate())<0){
            throw new MessageCenterException(ErrorCodeEnum.SECKILL_NOT_STARTED);
        }

        if (now.compareTo(vo.getEndDate())>0){
            throw new MessageCenterException(ErrorCodeEnum.SECKILL_IS_STOP);
        }

        //生成随机码
        String random = UUID.randomUUID().toString().replaceAll("-", "");
        // 将随机字符串跟用户关联起来，需要保存到Redis中
        stringRedisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_PATH_HASH.getRealKey(vo.getId()+""), user.getId()+"",random);
        return ResponseVo.ok(random);
    }
}
